import { defineComponent, nextTick, onMounted, ref } from 'vue';
import Sortable from 'sortablejs';
import { dragClass, dragGroup, dragGhostClass } from './hooks/config';

import { Tooltip } from 'ant-design-vue';

export default defineComponent({
  name: 'DargFields',
  props: {
    data: {
      type: Array,
      default() {
        return [];
      },
    },
    isShowPrompt: {
      type: Boolean,
      default() {
        return false;
      },
    },
  },
  setup(props) {
    const el = ref();
    onMounted(() => {
      nextTick(() => {
        new Sortable(el.value, {
          handle: '.' + dragClass,
          ghostClass: dragGhostClass,
          group: {
            name: dragGroup,
            put: false, // Do not allow items to be put into this list
          },
          sort: false, // To disable sorting: set sort to false
          onMove: function (evt) {
            let formId = evt.dragged.getAttribute('data-id');
            let toId = evt.to.getAttribute('data-id');
            let data = props.data.find((ri) => ri.id === formId);
            // 子功能 ｜ 审批事件不能拖拽到其它字段里面
            if (['child', 'workflowhistory'].includes(data.RESOURCEFIELD_XTYPE) && toId) {
              return false;
            }
          },
        });
      });
    });
    return () => (
      <div class="form-hidden-fields" ref={el}>
        {props.data.map((item) => {
          return (
            <div
              class={{
                'drag-item': true,
                [dragClass]: true,
                group: item.RESOURCEFIELD_XTYPE === 'fieldset',
                child: item.RESOURCEFIELD_XTYPE === 'child',
                workflowhistory: item.RESOURCEFIELD_XTYPE === 'workflowhistory',
              }}
              key={item.id}
              data-id={item.id}
              data-type={item.type}
            >
              <div className="textWrap">
                {item.RESOURCEFIELD_NAME}
                {item.RESOURCEFIELD_GROUPNAME && props.isShowPrompt ? (
                  <span class={{ red: !!item.RESOURCEFIELD_GROUPNAME }}>
                    {item.RESOURCEFIELD_GROUPNAME}
                  </span>
                ) : null}
              </div>

              <Tooltip placement="topRight" title={item.RESOURCEFIELD_CODE}>
                <i type="primary" class="solid fal fa-ellipsis-v"></i>
              </Tooltip>
            </div>
          );
        })}
      </div>
    );
  },
});
